<template>
  <div class="agent-list-page">
    <div class="page-header">
      <div class="header-content">
        <h1>智能体管理</h1>
        <el-button type="primary" @click="$router.push('/agents/create')">
          <i class="el-icon-plus"></i>
          创建智能体
        </el-button>
      </div>
    </div>

    <div class="page-content">
      <!-- 筛选工具栏 -->
      <div class="filter-toolbar">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-input
              v-model="searchQuery"
              placeholder="搜索智能体..."
              prefix-icon="Search"
              clearable
              @input="handleSearch"
            />
          </el-col>
          <el-col :span="6">
            <el-select v-model="filterType" placeholder="选择类型" clearable>
              <el-option label="全部类型" value="" />
              <el-option
                v-for="type in agentTypes"
                :key="type.id"
                :label="type.name"
                :value="type.id"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="filterStatus" placeholder="选择状态" clearable>
              <el-option label="全部状态" value="" />
              <el-option label="活跃" value="active" />
              <el-option label="草稿" value="draft" />
              <el-option label="停用" value="inactive" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button @click="resetFilters">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 智能体列表 -->
      <div class="agents-grid" v-loading="loading">
        <div v-if="agents.length === 0 && !loading" class="empty-state">
          <i class="el-icon-cpu empty-icon"></i>
          <h3>还没有智能体</h3>
          <p>创建您的第一个AI学习助手吧！</p>
          <el-button type="primary" @click="$router.push('/agents/create')">
            立即创建
          </el-button>
        </div>

        <el-card
          v-for="agent in agents"
          :key="agent.id"
          class="agent-card"
          shadow="hover"
          @click="viewAgent(agent.id)"
        >
          <div class="agent-header">
            <div class="agent-avatar">
              <img v-if="agent.avatar" :src="agent.avatar" alt="智能体头像" />
              <i v-else class="el-icon-cpu default-avatar"></i>
            </div>
            <div class="agent-status">
              <el-tag :type="getStatusType(agent.status)" size="small">
                {{ getStatusText(agent.status) }}
              </el-tag>
            </div>
          </div>

          <div class="agent-content">
            <h3 class="agent-name">{{ agent.name }}</h3>
            <p class="agent-description">{{ agent.description }}</p>
            
            <div class="agent-meta">
              <div class="meta-item">
                <i class="el-icon-collection-tag"></i>
                {{ agent.agent_type_name }}
              </div>
              <div class="meta-item">
                <i class="el-icon-chat-line-round"></i>
                {{ agent.usage_count }} 次对话
              </div>
              <div class="meta-item" v-if="agent.rating > 0">
                <i class="el-icon-star-on"></i>
                {{ agent.rating.toFixed(1) }}
              </div>
            </div>
          </div>

          <div class="agent-actions" @click.stop>
            <el-button size="small" type="primary" @click="chatWithAgent(agent.id)">
              对话
            </el-button>
            <el-button size="small" @click="editAgent(agent.id)">
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleAction(command, agent)">
              <el-button size="small" type="info" text>
                <i class="el-icon-more"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="duplicate">复制</el-dropdown-item>
                  <el-dropdown-item command="share">分享</el-dropdown-item>
                  <el-dropdown-item divided command="delete" class="danger">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > pageSize">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 48]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { agentApi } from '@/services/api'
import { useAppStore } from '@/stores/app'
import { ElMessageBox } from 'element-plus'

const router = useRouter()
const appStore = useAppStore()

const loading = ref(false)
const agents = ref([])
const agentTypes = ref([])
const searchQuery = ref('')
const filterType = ref('')
const filterStatus = ref('')

const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

onMounted(() => {
  loadAgentTypes()
  loadAgents()
})

const loadAgentTypes = async () => {
  try {
    const response = await agentApi.getAgentTypes()
    agentTypes.value = response.data
  } catch (error) {
    console.error('Failed to load agent types:', error)
  }
}

const loadAgents = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchQuery.value,
      agent_type: filterType.value,
      status: filterStatus.value
    }
    
    const response = await agentApi.getAgents(params)
    agents.value = response.data.results || response.data
    total.value = response.data.count || agents.value.length
  } catch (error) {
    console.error('Failed to load agents:', error)
    appStore.showError('加载智能体列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadAgents()
}

const resetFilters = () => {
  searchQuery.value = ''
  filterType.value = ''
  filterStatus.value = ''
  currentPage.value = 1
  loadAgents()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadAgents()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadAgents()
}

const viewAgent = (id) => {
  router.push(`/agents/${id}`)
}

const editAgent = (id) => {
  router.push(`/agents/${id}/edit`)
}

const chatWithAgent = (id) => {
  router.push(`/chat/${id}`)
}

const handleAction = async (command, agent) => {
  switch (command) {
    case 'duplicate':
      // 复制智能体逻辑
      appStore.showInfo('复制功能开发中...')
      break
    case 'share':
      // 分享智能体逻辑
      appStore.showInfo('分享功能开发中...')
      break
    case 'delete':
      await handleDelete(agent)
      break
  }
}

const handleDelete = async (agent) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除智能体 "${agent.name}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    await agentApi.deleteAgent(agent.id)
    appStore.showSuccess('智能体删除成功')
    loadAgents()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete agent:', error)
      appStore.showError('删除智能体失败')
    }
  }
}

const getStatusType = (status) => {
  const statusMap = {
    active: 'success',
    draft: 'info',
    training: 'warning',
    inactive: 'danger',
    error: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    active: '活跃',
    draft: '草稿',
    training: '训练中',
    inactive: '停用',
    error: '错误'
  }
  return statusMap[status] || status
}
</script>

<style scoped lang="scss">
.agent-list-page {
  min-height: 100vh;
  background: #f5f7fa;
}

.page-header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  max-width: 1200px;
  margin: 0 auto;
  
  h1 {
    margin: 0;
    font-size: 1.5rem;
    color: var(--el-text-color-primary);
  }
}

.page-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.filter-toolbar {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.agents-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
  color: var(--el-text-color-secondary);
  
  .empty-icon {
    font-size: 5rem;
    margin-bottom: 20px;
    opacity: 0.5;
  }
  
  h3 {
    margin: 0 0 8px 0;
    font-size: 1.5rem;
  }
  
  p {
    margin: 0 0 20px 0;
    font-size: 14px;
  }
}

.agent-card {
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px 0 rgba(0, 0, 0, 0.15);
  }
  
  :deep(.el-card__body) {
    padding: 20px;
  }
}

.agent-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.agent-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  background: var(--el-color-primary-light-9);
  display: flex;
  align-items: center;
  justify-content: center;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  
  .default-avatar {
    font-size: 24px;
    color: var(--el-color-primary);
  }
}

.agent-content {
  margin-bottom: 16px;
}

.agent-name {
  margin: 0 0 8px 0;
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--el-text-color-primary);
  line-height: 1.4;
}

.agent-description {
  margin: 0 0 12px 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.agent-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  
  i {
    font-size: 14px;
  }
}

.agent-actions {
  display: flex;
  gap: 8px;
  padding-top: 12px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

:deep(.danger) {
  color: var(--el-color-danger);
}

@media (max-width: 768px) {
  .agents-grid {
    grid-template-columns: 1fr;
  }
  
  .header-content {
    flex-direction: column;
    height: auto;
    gap: 15px;
    padding: 15px 0;
  }
  
  .filter-toolbar {
    .el-row {
      flex-direction: column;
      gap: 12px;
    }
  }
}
</style>